/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.loja.view.component.aggregation;

import br.com.loja.view.component.factory.ViewHadler;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JList;
import javax.swing.ListSelectionModel;

/**
 *
 * @author DavidLuiz
 */
public class EnumToMany<E> extends JList<E> implements ViewHadler<List<E>> {

    public EnumToMany(Class<E> clazz) {
        super(clazz.getEnumConstants());
        setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    }

    @Override
    public void setValueModel(List<E> value) {
        setSelectedIndices(getSelectedIndices(value));
        updateUI();

    }

    private int[] getSelectedIndices(List<E> value) {
        List<Integer> selectedList = new ArrayList<>();

        for (E elementSelected : value) {
            addSelectedIndex(elementSelected, selectedList);
        }

        int selectedCount = selectedList.size();
        int[] indices = new int[selectedCount];

        for (int i = 0; i < selectedCount; i++) {
            indices[i] = selectedList.get(i);
        }

        return indices;
    }

    private void addSelectedIndex(E elementSelected, List<Integer> selectedList) {
        for (int i = 0; i < getModel().getSize(); i++) {

            E currentElement = getModel().getElementAt(i);

            if (elementSelected.equals(currentElement)) {
                selectedList.add(i);
            }
        }
    }

    @Override
    public List<E> getValueModel() {
        return getSelectedValuesList();
    }

}
